package com.example.yyy

import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.os.Environment
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import kotlinx.android.synthetic.main.activity_file_path.*
import org.jetbrains.anko.startActivity
import java.io.File


class FilePathActivity : AppCompatActivity() {
    private val REQUEST_EXTERNAL_STORAGE = 1
    private val PERMISSIONS_STORAGE:List<String> = listOf(
        android.Manifest.permission.READ_EXTERNAL_STORAGE,
        android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
        android.Manifest.permission.ACCESS_COARSE_LOCATION,
        android.Manifest.permission.ACCESS_FINE_LOCATION
    )


    private val PERMISSIONS_STORAGE_New:MutableList<String> = mutableListOf()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_file_path)
        for (item in PERMISSIONS_STORAGE){
            val permission0:Int= ActivityCompat.checkSelfPermission(this,item)
            if (permission0 != PackageManager.PERMISSION_GRANTED){
                PERMISSIONS_STORAGE_New.add(item)
            }
        }
        if (PERMISSIONS_STORAGE_New.isNotEmpty()){
            ActivityCompat.requestPermissions(this,
                PERMISSIONS_STORAGE_New.toTypedArray(),REQUEST_EXTERNAL_STORAGE)
        }
        startActivity<DownloadManagerActivity>()
        saveText()
        saveImage()
        fileWalk()
        openApplication()
    }

    private fun saveText(){
        //获取当前app私有存储路径
        val privatePath = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
            .toString()+"/文件.txt"
        //文本写入文件
        val content = "存入了一个文本"
        File(privatePath).writeText(content)
        //文本读取文件
        val contentPa = File(privatePath).readText()
        val publicPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
            .toString()+"/文件.txt"
        //文本写入文件
        File(publicPath).writeText(content)
        //文本读取文件
        val contentPu = File(publicPath).readText()
        tv_fp_path.text = "系统公共存储路径$publicPath \n\n$contentPu\n\n当前app私有存储路径$privatePath\n\n$contentPa"
    }

    private fun saveImage(){
        val publicPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
            .toString()+"图片.jpeg"
        val bitmap:Bitmap = BitmapFactory.decodeResource(resources,R.drawable.tp)
        FileUtil().saveImage(publicPath,bitmap)

        //利用字节数组读取位图
        //readBytes读取字节数组形式的文件内容
        val readBytes = File(publicPath).readBytes()
        //利用BitmapFactory解析图片
        val bitmapB = BitmapFactory.decodeByteArray(readBytes, 0, readBytes.size)
//        img_fp_path.setImageBitmap(bitmapB)


        //利用输入流读取位图
        val openImage = FileUtil().openImage(publicPath)
//        img_fp_path.setImageBitmap(openImage)

        //直接从文件路径获取位图
        //利用BitmapFactory路径解析图片
        val bitmapF = BitmapFactory.decodeFile(publicPath)
        img_fp_path.setImageBitmap(bitmapF)
    }

    private fun fileWalk(){
        val publicPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
            .toString()
        val fileNames:MutableList<String> = mutableListOf()
        //在该目录下走一圈，得到文件目录树结构
        val fileTree = File(publicPath).walk()
        fileTree.maxDepth(1)//需遍历的目录层级为1，即无须检查子目录
            .filter { it.isFile }//只挑选文件，不处理文件夹
            .filter { it.extension == "txt" }//选择扩展名为txt的文件it.extension in listOf("png","jpg")
            .forEach { fileNames.add(it.name)}//循环处理符合条件的文件
        tv_fp_path.append(fileNames.toString())
    }

    private fun openApplication(){
        val instance = MainApplication.instance()
        tv_fp_path.append("\n\n${{instance.allString}}")
        instance.allString ="2333"
        tv_fp_path.append("\n\n${instance.allString}")
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        if (grantResults.isEmpty()) return
        for (i in grantResults) {
            if (PackageManager.PERMISSION_GRANTED != i) {
                //用户未授予权限定义中对应的权限
                //未授权，不能执行需要权限的操作。
            } else {
                //已授权可以执行相应操作
                //获取系统公共存储路径
            }
        }
    }
}